package com.example.asus.happy;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.asus.happy.service.address.Address;
import com.example.asus.happy.service.application.MyApplication;
import com.example.asus.happy.service.finaldata.FinalData;
import com.example.asus.happy.service.model.Content;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import static com.example.asus.happy.R.id.discussBtn;
import static com.example.asus.happy.R.id.laudBtn;
import static com.example.asus.happy.R.layout.activity_smile;


public class SmileActivity extends Fragment {
    private SwipeRefreshLayout mSwipeLayout;
    private Context mContext;//上下文
    private String userName;
    private ListView jokeList;
    private String url;//请求显示内容地址
    private String url1;//请求点赞地址
    private List<Content> list;
    private MyAdapter myAdapter;
    private Intent intent;
    private TextView titleTV;



    public void init(){
        url = Address.ADDRESS+"cuntent_json";
    }


    //处理下拉刷新的Handler
    private Handler mHandler = new Handler()
    {
        public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                case 1:
                    mSwipeLayout.setRefreshing(false);
                    Toast.makeText(mContext, FinalData.JOCK_REFRESH, Toast.LENGTH_SHORT).show();
                    break;
            }
        };
    };


    //处理显示内容Handler
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 0:
                        String response = (String)msg.obj;
                        list = getCarte(response);
                        myAdapter = new MyAdapter();
                        jokeList.setAdapter(myAdapter);
                        //刷新成功
                        mHandler.sendEmptyMessage(FinalData.ONE_INT);
                        break;
                    default:
                        break;
                }
            }

    };

    //处理点赞的Handler
    private Handler handler1 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case FinalData.ZERO_INT:
                    String response = (String)msg.obj;
                    if (FinalData.ZERO_STRING.equals(response)){
                        HttpPostRequest();
                    }

                    break;
                default:
                    break;
            }
        }

    };



    //处理显示内容HttpPostRequest
    private void HttpPostRequest(){
        //处理显示内容的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,FinalData.CODE));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == FinalData.TWO_HUNDRED){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,FinalData.CODE);
                        Message message = new Message();
                        message.what = FinalData.ZERO_INT;
                        message.obj = count.toString();
                        handler.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }


    //处理点赞HttpPostRequest1
    private void HttpPostRequest1(final String url1){
        //处理点赞的线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url1);
                List<NameValuePair> carteList = new ArrayList<NameValuePair>();
                try{
                    httpPost.setEntity(new UrlEncodedFormEntity(carteList,FinalData.CODE));
                    HttpResponse httpResponse = httpClient.execute(httpPost);
                    if (httpResponse.getStatusLine().getStatusCode() == FinalData.TWO_HUNDRED){
                        HttpEntity httpEntity = httpResponse.getEntity();
                        String count = EntityUtils.toString(httpEntity,FinalData.CODE);
                        Message message = new Message();
                        message.what = FinalData.ZERO_INT;
                        message.obj = count.toString();
                        handler1.sendMessage(message);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }


    private List<Content> getCarte(String product){
        try{
            JSONArray jarray = new JSONArray(product);
            List<Content> cartes = new ArrayList<Content>();
            for (int i = 0;i<jarray.length();i++){
                JSONObject obj = new JSONObject(jarray.get(i).toString());
                Content content = new Content();
                content.setC_id(obj.getInt("c_id"));
                content.setU_userName(obj.getString("u_userName"));
                content.setC_ct(obj.getString("c_ct"));
                content.setC_num(obj.getInt("c_num"));
                content.setC_sum(obj.getInt("c_sum"));
                cartes.add(content);
            }
            return cartes;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
        userName = ((MyApplication) getActivity().getApplication()).getUserName();
    }

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(activity_smile,null);
        //初始化
        init();
        //初始化ListView
        jokeList = (ListView) v.findViewById(R.id.jokeList);
        titleTV = (TextView)v.findViewById(R.id.titleTV);
        HttpPostRequest();//初始化数据

        //下拉刷新
        mSwipeLayout = (SwipeRefreshLayout) v.findViewById(R.id.id_swipe_ly);
        mSwipeLayout.setColorScheme(new int[]{android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light});
        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //执行刷新方法
                HttpPostRequest();
            }
        });

        //标题点击事件（返回顶部）
        titleTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                jokeList.setSelection(FinalData.ZERO_INT);
            }
        });

        return v;
    }

    //页面刷新
    @Override
    public void onResume() {
        super.onResume();
        //重新加载数据
        HttpPostRequest();
    }

    //自定义适配器
   public class MyAdapter extends BaseAdapter {
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, final View convertView, ViewGroup parent) {
            final View view = getLayoutInflater(null).inflate(R.layout.jokelist_item,null);

            final Content c = list.get(position);
            ((TextView)view.findViewById(R.id.u_NameTV)).setText(c.getU_userName());
            ((TextView)view.findViewById(R.id.contentTV)).setText(c.getC_ct());
            ((TextView)view.findViewById(laudBtn)).setText(FinalData.LAUD+FinalData.LEFT+c.getC_num()+FinalData.RIGHT);
            //分享按钮点击事件
            View shareBtn=view.findViewById(R.id.shareBtn);
            shareBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // 分享文字，调用系统接口
                    Toast.makeText(mContext, "分享", Toast.LENGTH_SHORT).show();
                    Intent shareIntent = new Intent();
                    shareIntent.setAction(Intent.ACTION_SEND);
                    shareIntent.putExtra(Intent.EXTRA_TEXT, c.getC_ct());
                    shareIntent.setType("text/plain");
                    //设置分享列表的标题，并且每次都显示分享列表
                    startActivity(Intent.createChooser(shareIntent, "分享到"));
                }
            });

            //点赞按钮
            final View laudBtn = ((TextView) view.findViewById(R.id.laudBtn));
            laudBtn.setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    //判断用户是否登录（登录才能点赞）
                    if ("null".equals(userName)){
                        //没有登录
                        Toast.makeText(mContext, FinalData.NOLOGIN, Toast.LENGTH_SHORT).show();
                        intent = new Intent(getActivity(),LoginActivity.class);
                        startActivity(intent);
                    }else {

                            url1 = Address.ADDRESS+"updateNum?c_id="+c.getC_id();
                            HttpPostRequest1(url1);
                    }
                }
            });

            ((TextView)view.findViewById(discussBtn)).setText(FinalData.DISCUSS+FinalData.LEFT+c.getC_sum()+FinalData.RIGHT);

            //评论按钮点击事件
            View discussBtn = ((TextView) view.findViewById(R.id.discussBtn));
            discussBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    //判断用户是否登录（登录才能评论）
                    if ("null".equals(userName)){
                        //没有登录
                        Toast.makeText(mContext, FinalData.NOLOGIN, Toast.LENGTH_SHORT).show();
                        intent = new Intent(getActivity(),LoginActivity.class);
                        startActivity(intent);
                    }else {
                        //执行评论
                        //跳转至笑话详情
                        intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putInt("c_id",c.getC_id());//内容id
                        bundle.putString("content", c.getC_ct());//内容
                        bundle.putString("laud", c.getC_num()+"");
                        bundle.putString("discuss",c.getC_sum()+"");
                        intent.setClass(getActivity(),jokeListDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            });

            //笑话内容点击事件
            View contentTV = ((TextView) view.findViewById(R.id.contentTV));
            contentTV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    //判断用户是否登录
                    if ("null".equals(userName)){
                        Toast.makeText(mContext, FinalData.NOLOGIN, Toast.LENGTH_SHORT).show();
                        intent = new Intent(mContext,LoginActivity.class);
                        startActivity(intent);
                    }else {
                        //跳转至笑话详情
                        intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putInt("c_id",c.getC_id());//内容id
                        bundle.putString("content", c.getC_ct());//内容
                        bundle.putInt("laud", c.getC_num());//赞数量
                        bundle.putInt("discuss",c.getC_sum());//评论数量
                        intent.setClass(getActivity(),jokeListDetailActivity.class);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                }
            });
            return view;
        }
    }

    //获取application
    public MyApplication getApp(){
        return (MyApplication) getActivity().getApplication().getApplicationContext();
    }
}
